import {computed, ref} from 'vue';
import api from "@/utils/api";
import type {CtrlPlan, Frequency} from "./type.ts";
import {message} from "ant-design-vue";

// 定义响应式变量
export const fetching = ref(false);
export const frequencySearchList = ref<Frequency[]>([]);
export const frequencyList = ref<Frequency[]>([]);
export const newFrequencyName = ref();

// 获取时机列表
export const fetchFrequencies = async () => {
    try {
        const response = await api.get('ctrlPlan/cpFrequency');
        frequencyList.value = response.data;
        return frequencyList.value;
    } catch (error) {
        console.error('获取时机列表失败:', error);
        throw error;
    }
};
export const onFrequencySearch = async (cnDesc: string) => {
    if(frequencyList.value===undefined || frequencyList.value.length===0){
        await fetchFrequencies();
    }
    if(frequencyList.value){
        frequencySearchList.value = frequencyList.value
            .filter(fq => fq.cnDesc.includes(cnDesc))
            .sort((a, b) => a.id - b.id);
    }
    if(cnDesc.length>0){
        newFrequencyName.value=cnDesc;
    }
};

export const onFrequencyChange = (value: any, cpFrequencies: Frequency[]) => {
    if(value){
        // 清空现有的频率数组
        cpFrequencies.length = 0;
        // 对 value 进行去重处理
        const uniqueValues= [...new Set(value)];

        // 遍历所有去重后的值
        uniqueValues.forEach(frequencyDesc => {
            const ifq = frequencyList.value.find(fq => fq.cnDesc === frequencyDesc);

            if (ifq) {
                cpFrequencies.push({
                    id: ifq.id,
                    cnDesc: ifq.cnDesc,
                });
            }else{
                if(typeof frequencyDesc === 'string'){
                    cpFrequencies.push({
                        id: undefined,
                        cnDesc: frequencyDesc,
                    });
                }
            }
        });
        newFrequencyName.value=undefined;
    }

};

export const isFrequencyNew = computed(() => {
    return (newFrequencyName && newFrequencyName.value!==undefined)
})

export const onFrequencyBlur = (ctrlPlan:CtrlPlan) => {
    ctrlPlan.frequencyValues=[];
    if (ctrlPlan.frequencies) {
        ctrlPlan.frequencies.forEach(fq => {
            ctrlPlan.frequencyValues?.push(fq.cnDesc);
        });
    }
    if(isFrequencyNew.value){
        ctrlPlan.frequencies.push({
            id:undefined,
            cnDesc:newFrequencyName.value,
        });
        ctrlPlan.frequencyValues.push(newFrequencyName.value);
    }
};

export const createNewFrequency = async (cnDesc: string) => {
    const ofq=frequencyList.value.find(fq => fq.cnDesc===cnDesc);
    if(ofq){
        return;
    }
    try {
        fetching.value = true;

        await api.post('/cpFrequency', {
            cnDesc: cnDesc,
        });
        await fetchFrequencies();
        message.success(`新控制时机【${cnDesc}】创建成功`);
        return true;
    } catch (error) {
        message.error('创建控制时机失败');
        console.error('创建控制时机失败:', error);
        return false;
    } finally {
        fetching.value = false;
    }
};

// 重置时机数据
export const resetFrequencyData = () => {
    frequencyList.value = [];
};

// 导出所有方法
export default {
    frequencyList,
    frequencySearchList,
    fetchFrequencies,
    onFrequencySearch,
    onFrequencyChange,
    onFrequencyBlur,
    createNewFrequency,
    resetFrequencyData
};